package com.cn.sl.server.api.system.user.model.dto

import com.cn.sl.server.api.system.role.model.entity.RoleEntity
import com.cn.sl.server.api.system.user.model.entity.AdminUserEntity
import com.cn.sl.server.api.system.user.model.entity.UserStatus
import com.cn.sl.server.api.system.user.util.encrypt
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull

class AddAdminUserParam(
    var avatarId: Long?,
    @field:NotBlank(message = "用户名不能为空")
    var username: String?,
    override var phone: String?,
    var homePageId: Long?,
    var roleIds: List<Long>?,
    var departmentId: Long?,
    @NotNull(message = "状态不能为空")
    var status: UserStatus?
) : PhoneCheckParam(null, phone) {
    fun toDto(): AddAdminUserDto {
        return AddAdminUserDto(
            avatarId = avatarId,
            username = username!!,
            phone = phone!!,
            homePageId = homePageId,
            roleIds = roleIds,
            departmentId = departmentId,
            status = status!!
        )
    }
}

data class AddAdminUserDto(
    val avatarId: Long?,
    val username: String,
    val phone: String,
    val homePageId: Long?,
    val roleIds: List<Long>?,
    val departmentId: Long?,
    var status: UserStatus
) {
    fun toEntity(fetchRoles: (roleIds: List<Long>) -> List<RoleEntity>): AdminUserEntity {
        val dto = this
        val (password, salt) = encrypt(dto.phone)
        return AdminUserEntity().apply {
            this.avatarId = dto.avatarId
            this.username = dto.username
            this.phone = dto.phone
            this.homePageId = dto.homePageId
            this.roles = dto.roleIds?.let { fetchRoles(it) } ?: listOf()
            this.departmentId = dto.departmentId
            this.status = dto.status
            this.password = password
            this.salt = salt
        }
    }
}